import {
  userLoginByAccount,
  userLoginByPhone,
  userLogout,
  checkIsDefaultPassword,
} from '@/services/user';
import { getToken, setToken, removeToken } from '@/utils/auth';

const UserModel = {
  namespace: 'user',
  state: {
    isDefaultPassword: false,
    token: getToken() || '',
  },
  effects: {
    *login({ payload }, { call, put }) {
      try {
        const { type, params } = payload;
        switch (type) {
          case 'phone': // 手机号登录
            const { saToken: tokenByPhoneLogin } = yield call(userLoginByPhone, params);
            yield put({ type: 'saveToken', payload: { token: tokenByPhoneLogin } });
            return Promise.resolve();
          default: // 账号密码登录
            const { saToken: loginToken } = yield call(userLoginByAccount, params);
            yield put({ type: 'saveToken', payload: { token: loginToken } });
            return Promise.resolve();
        }
      } catch (e) {
        return Promise.reject(e);
      }
    },
    *logout({ payload }, { call, put }) {
      const { withoutLogout } = payload || {};
      try {
        if (!withoutLogout) {
          yield call(userLogout);
        }
        yield put({ type: 'resetByLogout' });
        yield put({ type: 'global/closeCheck' });
        yield put({ type: 'menu/resetByLogout' });
        return Promise.resolve();
      } catch (e) {
        yield put({ type: 'resetByLogout' });
        yield put({ type: 'global/closeCheck' });
        yield put({ type: 'menu/resetByLogout' });
        return Promise.reject();
      }
    },
    *checkPasswordStatus(action, { call, put }) {
      try {
        const { initPwd } = yield call(checkIsDefaultPassword);
        yield put({ type: 'updatePasswordStatus', payload: !!initPwd });
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
  reducers: {
    saveToken(state, action) {
      const { token } = action.payload;
      setToken(token);
      return {
        ...state,
        ...action.payload,
      };
    },
    resetByLogout(state) {
      removeToken();
      return {
        ...state,
        isDefaultPassword: false,
        token: '',
      };
    },
    updatePasswordStatus(state, action) {
      return {
        ...state,
        isDefaultPassword: !!action.payload,
      };
    },
  },
  subscriptions: {
    checkDefaultPasswordWithLogin({ dispatch }) {
      if (getToken()) {
        dispatch({ type: 'checkPasswordStatus' });
      }
    },
  },
};
export default UserModel;
